# frozen_string_literal: true

class ScriptSandbox < BasicObject
  class << self
    def eval_script(script, **params)
      new(params).eval_script(script)
    end

    def eval_bool_script(script, **params)
      new(params).eval_bool_script(script)
    end

    private

    def logger
      Rails.logger
    end
  end

  def initialize(**params)
    @params = params
  end

  def eval_bool_script(script)
    eval_script(script).present?
  rescue StandardError => e
    logger.error e
    false
  end

  def eval_script(script)
    return script if script.blank? || !script.is_a?(::String)

    instance_eval script
  end

  def respond_to_missing?(*several_variants)
    super
  end

  private

  def method_missing(symbol, *args)
    if @params
      return @params[symbol] if @params.key? symbol

      return @params[symbol.to_s] if @params.key? symbol.to_s
    end

    super
  end

  def logger
    self.class.logger
  end
end
